/**
 *
 *
 * 
 *
 * 
 */

package io.dbw.common.utils;

import io.dbw.common.enums.ResultStatusEnum;
import io.dbw.common.exception.BusinessException;
import io.dbw.modules.business.vo.CommonUserVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * Shiro工具类
 *
 * 
 */
public class ShiroUtils {

	public static Session getSession() {
		return SecurityUtils.getSubject().getSession();
	}

	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}

	public static CommonUserVO getCommonUserVO() {
		CommonUserVO user = (CommonUserVO) SecurityUtils.getSubject().getPrincipal();
		if (user == null) {
			throw new BusinessException(ResultStatusEnum.USER_OVERDUE);
		}
		return user;
	}

	public static Long getUserId() {
		return getCommonUserVO().getUserId();
	}
	
	public static void setSessionAttribute(Object key, Object value) {
		getSession().setAttribute(key, value);
	}

	public static Object getSessionAttribute(Object key) {
		return getSession().getAttribute(key);
	}

	public static boolean isLogin() {
		return SecurityUtils.getSubject().getPrincipal() != null;
	}

	public static String getKaptcha(String key) {
		Object kaptcha = getSessionAttribute(key);
		if(kaptcha == null){
			throw new BusinessException("验证码已失效");
		}
		getSession().removeAttribute(key);
		return kaptcha.toString();
	}

}
